package com.xianlai.microcosm_log

import java.util.*

object FlutterLog {

    private val logBuffer: MutableList<Any> = LinkedList()

    /**
     * verbose level
     */
    @JvmStatic
    fun v(tag: String, msg: String) = log("v", tag, msg)

    /**
     * debug level
     */
    @JvmStatic
    fun d(tag: String, msg: String) = log("d", tag, msg)

    /**
     * info level
     */
    @JvmStatic
    fun i(tag: String, msg: String) = log("i", tag, msg)

    /**
     * warn level
     */
    @JvmStatic
    fun w(tag: String, msg: String) = log("w", tag, msg)

    /**
     * error level
     */
    @JvmStatic
    fun e(tag: String, msg: String) = log("e", tag, msg)


    private fun log(level: String, tag: String, msg: String) {
        val params = mutableMapOf<String, Any>()
        params["level"] = level
        params["tag"] = tag
        params["msg"] = msg
        params["timestamp"] = System.currentTimeMillis()
        sendLogToFlutter(params)
    }

    /**
     * flutter初始化之前的log,先暂存到logBuffer中
     * flutter初始化之后，会给Android/iOS发送"onConnected"消息
     */
    private fun sendLogToFlutter(params: MutableMap<String, Any>) {
        if (ChannelManager.hasConnectFlutter) {
            ChannelManager.sendMethodToFlutter("log", params)
        } else {
            //可能通过多个线程调用
            synchronized(logBuffer) {
                logBuffer.add(params)
            }
            if (ChannelManager.connectFlutterListener == null) {
                ChannelManager.connectFlutterListener = {
                    logBuffer.forEach {
                        ChannelManager.sendMethodToFlutter("log", it)
                    }
                    logBuffer.clear()
                }
            }
        }
    }

}